<template>
  <el-dialog :visible.sync="visible" title="绑定邮箱" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" v-loading="loading" ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="code" label="验证码">
        <el-row>
          <el-col :span="14">
            <el-input v-model="dataForm.code" controls-position="right" :maxlength="6" label="验证码" clearable>
            </el-input>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-button type="primary" round @click="sendCode()" :disabled='!this.canClick'>{{content}}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="dataFormSubmitHandle()">{{ $t('confirm') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      loading: false,
      visible: false,
      dataForm: {
        email: '',
        code: ''
      },
      content: '发送验证码',
      totalTime: 60,
      canClick: true,
      clock: null
    }
  },
  components: {},
  computed: {
    dataRule () {
      // var checkMobile = (rule, value, callback) => {
      //   if (!value) {
      //     return callback(new Error('手机号不能为空'))
      //   } else {
      //     const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      //     if (reg.test(value)) {
      //       callback()
      //     } else {
      //       return callback(new Error('请输入正确的手机号'))
      //     }
      //   }
      // }
      return {
        email: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' },
          { min: 6, max: 6, message: '请输入6位验证码' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        window.clearInterval(this.clock)
        this.content = '发送验证码'
        this.canClick = true
        // this.dataForm = {
        //   ...this.dataForm,
        //   ...this.initParams
        // }
        // if (this.dataForm.id) {
        //   this.getInfo()
        // } else {
        //   if (!this.dataForm.pid) {
        //     this.deptListTreeSetDefaultHandle()
        //   }
        //   this.getSortInfo()
        // }
      })
    },
    sendCode () {
      this.$refs['dataForm'].validateField('email', (valid) => {
        if (valid) {
          return false
        }
        this.$http.put(`/user/center/sendEmailCode/${this.dataForm.email}`, null).then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.setSendTime()
          this.$message({
            message: '验证码发送成功',
            type: 'success',
            duration: 3000,
            onClose: () => {

            }
          })
        }).catch(() => { })
      })
    },
    setSendTime () {
      if (!this.canClick) return // 改动的是这两行代码
      this.canClick = false
      this.content = this.totalTime + 's后重新发送'
      this.clock = window.setInterval(() => {
        this.totalTime--
        this.content = this.totalTime + 's后重新发送'
        if (this.totalTime < 0) {
          window.clearInterval(this.clock)
          this.content = '重新发送验证码'
          this.totalTime = 60
          this.canClick = true // 这里重新开启
        }
      }, 1000)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.loading = true
        this.$http['put']('/user/center/email', this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshData')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
